package com.runa.rccprotocol.analysis.En13757.decoder;

import com.runa.protocol.util.ByteUtil;

/**
 * @author diandian
 * @Date 2021/11/16 11:13
 */
public class DecoderSet {

    private int current = -1;

    protected byte[] dataByte;

    public int length;

    public void init(byte[] dataByte, int length){
        this.dataByte = dataByte;
        this.length = length;
    }

    protected boolean hasNext() {
        return current != length;
    }

    protected void addCurrentIndex(int add) {
        current += add;
    }

    protected byte next() {
        this.addCurrentIndex(1);
        return current();
    }
    protected byte current() {
        return dataByte[current];
    }

    public int getCurrentIndex() {
        return this.current;
    }

    protected void setCurrentIndex(int index) {
        this.current = index;
    }

    protected byte[] nextArray(int length) {
        byte[] res = new byte[length];
        for (int i = 0; i < length; i++) {
            byte next = next();
            res[i] = next;
        }
        return res;
    }

    protected byte sum(int start,int length){
        byte sum = ByteUtil.sum(dataByte, start, length);
        return sum;
    }

    protected int toInt(int index,int length,boolean order) {
        int res = ByteUtil.bcdToInt(this.dataByte, index, length, order);
        this.addCurrentIndex(length);
        return res;
    }
    protected int nextInt(int length,boolean order) {
        return toInt(current, length, order);
    }

    protected String nextHexString(int length,boolean order) {
        current++;
        String res;
        if (order) {
            res = ByteUtil.byteToHexString(this.dataByte, current, length);
        } else {
            res = ByteUtil.byteToHexStringFlip(this.dataByte, current, length);
        }
        this.addCurrentIndex(length-1);
        return res;
    }

}